<template>
  <div class="student-admin-container">
    <!-- 页面标题与操作按钮 -->
    <div class="page-header">
      <h2>学生管理</h2>
      <div class="header-actions">
        <el-button
            type="danger"
            @click="handleBatchDelete"
            v-if="selectedStudentIds.length > 0"
            :loading="batchDeleteLoading"
        >
          批量删除
        </el-button>
        <el-button
            type="primary"
            @click="handleAdd"
            style="margin-left: 12px"
        >
          新增学生
        </el-button>
      </div>
    </div>

    <!-- 搜索与筛选区域 -->
    <div class="search-bar">
      <el-input
          v-model="searchName"
          placeholder="输入学生姓名搜索"
          style="width: 300px; margin-right: 16px"
          @keyup.enter="handleSearch"
          clearable
      ></el-input>
      <el-button type="default" @click="handleSearch">搜索</el-button>
      <el-button type="text" @click="handleResetSearch" style="margin-left: 8px">重置</el-button>

      <!-- 超级管理员专属：校区筛选下拉框 -->
      <el-select
          v-if="isSuperAdmin"
          v-model="selectedCampusId"
          placeholder="选择校区"
          style="width: 200px; margin-left: 20px"
          @change="handleCampusChange"
          clearable
      >
        <el-option
            v-for="campus in campusList"
            :key="campus.id"
            :label="campus.name"
            :value="campus.id"
        ></el-option>
      </el-select>
    </div>

    <!-- 学生列表表格 -->
    <el-table
        v-loading="loading"
        :data="studentList"
        border
        style="width: 100%; margin-top: 16px"
        @selection-change="handleSelectionChange"
        row-key="id"
    >
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column label="ID" prop="id" width="80" align="center"></el-table-column>
      <el-table-column label="用户名" prop="username" align="center"></el-table-column>
      <el-table-column label="真实姓名" prop="realName" align="center"></el-table-column>
      <el-table-column label="性别" prop="gender" align="center" width="80">
        <template #default="scope">
          <el-tag size="small">{{ scope.row.gender === 'male' ? '男' : '女' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="年龄" prop="age" align="center" width="80"></el-table-column>
      <el-table-column label="手机号" prop="phone" align="center"></el-table-column>
      <el-table-column label="邮箱" prop="email" align="center"></el-table-column>
      <el-table-column label="所属校区" align="center">
        <template #default="scope">
          {{ scope.row.campusId?.name || '未知校区' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180">
        <template #default="scope">
          <el-button type="text" @click="handleEdit(scope.row)" size="small">编辑</el-button>
          <el-button type="text" danger @click="handleDelete(scope.row.id)" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          background
      ></el-pagination>
    </div>

    <!-- 新增/编辑学生弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogType === 'add' ? '新增学生' : '编辑学生'"
        width="500px"
        :close-on-click-modal="false"
        :before-close="handleDialogClose"
    >
      <el-form
          ref="studentFormRef"
          :model="formData"
          :rules="formRules"
          label-width="120px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
              v-model="formData.username"
              :disabled="dialogType === 'edit'"
              placeholder="请输入用户名（3-20字符）"
              maxlength="20"
          ></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input
              v-model="formData.realName"
              placeholder="请输入真实姓名（2-10字符）"
              maxlength="10"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="formData.gender">
            <el-radio label="male">男</el-radio>
            <el-radio label="female">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input
              v-model.number="formData.age"
              type="number"
              placeholder="请输入年龄（5-100岁）"
              :min="5"
              :max="100"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
              v-model="formData.phone"
              placeholder="请输入11位手机号"
              maxlength="11"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
              v-model="formData.email"
              placeholder="请输入有效邮箱"
              maxlength="50"
          ></el-input>
        </el-form-item>
        <el-form-item
            v-if="isSuperAdmin"
            label="所属校区"
            prop="campusId"
        >
          <el-select
              v-model="formData.campusId"
              placeholder="请选择校区"
              style="width: 100%"
          >
            <el-option
                v-for="campus in campusList"
                :key="campus.id"
                :label="campus.name"
                :value="campus.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
            type="primary"
            @click="handleFormSubmit"
            :loading="formLoading"
        >
          确认
        </el-button>
      </template>
    </el-dialog>

    <!-- 批量删除确认弹窗 -->
    <el-dialog
        v-model="batchDeleteDialogVisible"
        title="批量删除确认"
        width="400px"
        :close-on-click-modal="false"
    >
      <p>确定要删除选中的 {{ selectedStudentIds.length }} 条学生数据吗？</p>
      <p style="color: #f56c6c">此操作不可撤销，删除后数据将永久丢失！</p>
      <template #footer>
        <el-button @click="batchDeleteDialogVisible = false">取消</el-button>
        <el-button
            type="danger"
            @click="handleBatchDeleteConfirm"
            :loading="batchDeleteLoading"
        >
          确认删除
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// 基础依赖导入
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// Store 导入（确保路径正确）
import { useStudentStore } from '@/stores/student'
import { useUserStore } from '@/stores/user'
import { pinia } from '@/main'

// 初始化 Store
const studentStore = useStudentStore(pinia)
const userStore = useUserStore(pinia)

// 页面状态管理
const studentFormRef = ref(null)
const dialogVisible = ref(false)
const dialogType = ref('add')
const searchName = ref('')
const selectedCampusId = ref('')
const selectedStudentIds = ref([])
const batchDeleteDialogVisible = ref(false)
const formLoading = ref(false)
const batchDeleteLoading = ref(false)

// 从 Store 获取状态和方法
const {
  studentList,
  total,
  currentPage,
  pageSize,
  loading,
  campusList,
  formData,
  isSuperAdmin,
  fetchStudentList,
  fetchCampusList,
  addStudent,
  updateStudent,
  deleteStudent,
  getStudentById,
  resetFormData,
  setPageParams,
  setSearchName
} = studentStore

// 表单验证规则
const formRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在3-20个字符之间', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在2-10个字符之间', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    { type: 'number', min: 5, max: 100, message: '年龄需在5-100之间', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  campusId: [
    { required: true, message: '请选择校区', trigger: 'change' }
  ]
})

// 页面初始化
onMounted(async () => {
  // 加载校区列表（仅超级管理员）
  if (isSuperAdmin.value) {
    await fetchCampusList()
  }
  // 加载学生列表
  await fetchStudentList()

  // 监听 Token 变化，自动刷新数据
  watch(
      () => userStore.token,
      async (newToken) => {
        if (newToken) {
          await fetchStudentList()
        }
      }
  )
})

// 搜索功能
const handleSearch = async () => {
  await setSearchName(searchName.value.trim())
  ElMessage.success(`搜索关键词: ${searchName.value || '无'}`)
}

// 重置搜索
const handleResetSearch = async () => {
  searchName.value = ''
  selectedCampusId.value = ''
  await setSearchName('')
}

// 校区筛选变化
const handleCampusChange = async () => {
  // 手动筛选校区时，更新查询参数并重新加载
  searchName.value = ''
  await setPageParams(1, pageSize.value)
}

// 分页大小变化
const handleSizeChange = async (size) => {
  await setPageParams(currentPage.value, size)
}

// 页码变化
const handleCurrentChange = async (page) => {
  await setPageParams(page, pageSize.value)
}

// 新增学生
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  resetFormData(true)
  studentFormRef.value?.clearValidate()
}

// 编辑学生
const handleEdit = async (row) => {
  if (!row?.id) {
    ElMessage.warning('无效的学生数据')
    return
  }
  dialogType.value = 'edit'
  dialogVisible.value = true
  const student = await getStudentById(row.id)
  if (student) {
    resetFormData(false, student)
  }
  studentFormRef.value?.clearValidate()
}

// 表单提交
const handleFormSubmit = async () => {
  // 表单验证
  const valid = await studentFormRef.value?.validate().catch(() => false)
  if (!valid) return

  formLoading.value = true
  try {
    if (dialogType.value === 'add') {
      await addStudent()
    } else {
      await updateStudent()
    }
    dialogVisible.value = false
    ElMessage.success(dialogType.value === 'add' ? '新增成功' : '更新成功')
  } catch (error) {
    ElMessage.error(dialogType.value === 'add' ? '新增失败' : '更新失败')
    console.error(error)
  } finally {
    formLoading.value = false
  }
}

// 关闭弹窗
const handleDialogClose = () => {
  studentFormRef.value?.clearValidate()
  dialogVisible.value = false
}

// 单行删除
const handleDelete = async (id) => {
  if (!id) return

  try {
    await ElMessageBox.confirm(
        '确定要删除该学生吗？',
        '确认删除',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    const success = await deleteStudent(id)
    if (success) {
      ElMessage.success('删除成功')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }
}

// 批量选择变化
const handleSelectionChange = (selection) => {
  selectedStudentIds.value = selection.map(item => item.id)
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedStudentIds.value.length === 0) {
    ElMessage.warning('请先选择学生')
    return
  }
  batchDeleteDialogVisible.value = true
}

// 确认批量删除
const handleBatchDeleteConfirm = async () => {
  batchDeleteLoading.value = true
  try {
    for (const id of selectedStudentIds.value) {
      await deleteStudent(id)
    }
    ElMessage.success(`已删除 ${selectedStudentIds.value.length} 条数据`)
    batchDeleteDialogVisible.value = false
    selectedStudentIds.value = []
  } catch (error) {
    ElMessage.error('批量删除失败')
    console.error(error)
  } finally {
    batchDeleteLoading.value = false
  }
}
</script>

<style scoped>
.student-admin-container {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 40px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 16px;
}

.pagination {
  margin-top: 16px;
  text-align: right;
}
</style>
